﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Arc.WinForms.Controls;
using Arc.DairyMan.DairyMan.Model;
using Arc.DairyMan.DairyMan.BusinessLogic;
using System.Collections;
using Arc.DairyMan.DairyMan.Common;

namespace Arc.DairyMan.DairyMan.UI
{
    public partial class frmMilkCollection : ArcForm
    {
        #region Variables & Properties
        DataSet _DS = new DataSet();
        DataSet _DSSearch = new DataSet();
        MilkCollection Model;
        blMilkCollection BL;
        int _SabhasadId = 0;
        blSabhasad _blSabhasad;
        blSettings _blSettings;
        blMilkCollection _blMilkCollection;
        decimal _FatRate = 0;
        decimal FatRate
        { get { return _FatRate; } set { _FatRate = value; lblFatRate.Text = _FatRate.ToString(); } }
        bool _DemoExpired = false;
        #endregion

        #region Constructor
        public frmMilkCollection()
        {
            InitializeComponent();
            BL = new blMilkCollection();
            Model = (MilkCollection)BL.ModelObj;
            BL.DS = _DS;
            _blSabhasad = new blSabhasad();
            _blSabhasad.DS = _DSSearch;
            _blMilkCollection = new blMilkCollection();
            _blMilkCollection.DS = _DSSearch;
            _blSettings = new blSettings();
            _blSettings.DS = _DSSearch;
            BL.Search("1<>1");

            ArrayList _MilkTypes = new ArrayList();
            cmbMilkType.DisplayMember = "Name";
            cmbMilkType.ValueMember = "Value";
            foreach (var str in Enum.GetNames(typeof(MilkType)))
            {
                _MilkTypes.Add(new { Name = str, Value = Convert.ToInt32(Enum.Parse(typeof(MilkType), str)) });
            }
            cmbMilkType.DataSource = _MilkTypes;

            ArrayList _Shifts = new ArrayList();
            cmbShift.DisplayMember = "Name";
            cmbShift.ValueMember = "Value";
            foreach (var str in Enum.GetNames(typeof(Shift)))
            {
                _Shifts.Add(new { Name = str, Value = Convert.ToInt32(Enum.Parse(typeof(Shift), str)) });
            }
            cmbShift.DataSource = _Shifts;

            ResetForm();
        }
        #endregion

        #region Private Methods
        void ResetForm()
        {
            foreach (Control ctl in this.Controls.GetControls<ArcTextBox>())
                ctl.Text = string.Empty;

            _SabhasadId = 0;
            lblTotalMilk.Text = lblTotalAmount.Text = lblTotalSabhasad.Text = lblAvgFat.Text = string.Empty;
            Model.SetDefaultValues();

            _blSettings.Search("SettingsId = 1");
            if (_DSSearch.Tables.Contains("Settings") && _DSSearch.Tables["Settings"].Rows.Count > 0)
            {
                FatRate = Convert.ToDecimal(_DSSearch.Tables["Settings"].Rows[0]["FatRate"]);
            }

            //txtRate.Text = _FatRate.ToString();
            cmbShift_SelectedIndexChanged(null, null);
            txtCode.Focus();

            _blMilkCollection.Search(string.Empty);
            if (_blMilkCollection.DS.Tables.Contains("MilkCollection") && _blMilkCollection.DS.Tables["MilkCollection"].Rows.Count > 50) //LICENSE
            {
                _DemoExpired = true;
                MessageBox.Show("You have reached the maximum limit of the demo.\nPlease purchase the software for further use.");
            }
        }
        #endregion

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                ValidateForm();

                //if (_SabhasadId == 0)
                //{
                //    blSabhasad _blSabhasad = new blSabhasad();
                //    Sabhasad _newSabhasad = (Sabhasad)_blSabhasad.ModelObj;
                //    _newSabhasad.Code = txtCode.Text;
                //    _newSabhasad.Name = txtName.Text;
                //    _newSabhasad.MilkType = (MilkType)cmbMilkType.SelectedValue;
                //    _newSabhasad.TransactionMode = TransactionModes.Insert;

                //    _blSabhasad.Transaction(true);

                //    _SabhasadId = _blSabhasad.GetSabhasadIdByCode(txtCode.Text);
                //}

                if (_DemoExpired)
                {
                    throw new Exception("You have reached the maximum limit of the demo.\nPlease purchase the software for further use.");
                }

                Model.SabhasadId = _SabhasadId;
                Model.Date = dtDate.Value;
                Model.Shift = (Shift)cmbShift.SelectedValue;
                Model.MilkType = (MilkType)cmbMilkType.SelectedValue;
                Model.Quantity = Convert.ToDecimal(txtLiter.Text);
                Model.Fat = Convert.ToDecimal(txtFat.Text);
                Model.Rate = Convert.ToDecimal(txtRate.Text);
                Model.Amount = Convert.ToDecimal(txtAmt.Text);

                BL.Transaction(true);
                ResetForm();
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void ValidateForm()
        {
            if (dtDate.Value.Date > DateTime.Now.Date)
            {
                dtDate.Focus();
                throw new Exception("Date cannot be future date.");
            }
            else if (_SabhasadId == 0)
            {
                txtCode.Focus();
                throw new Exception("Please select an existing Sabhasad Code.");
            }
            else if (string.IsNullOrEmpty(txtLiter.Text))
            {
                txtLiter.Focus();
                throw new Exception("Please enter Liters.");
            }
            else if (string.IsNullOrEmpty(txtFat.Text))
            {
                txtFat.Focus();
                throw new Exception("Please enter FAT.");
            }
            else if (string.IsNullOrEmpty(txtRate.Text))
            {
                txtRate.Focus();
                throw new Exception("Please enter Milk Rate.");
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            frmSearch_Eng _frmSearch = new frmSearch_Eng();
            _frmSearch.Hidden_Field.AddRange(new[] { "SabhasadId", "MilkCollectionId" });
            _frmSearch.BusinessClass = BL;
            _frmSearch.ShowDialog();
            if (_frmSearch.PressedButton == Press_Button.Edit)
            {
                DataRow _dr = _DS.Tables["MilkCollection"].Rows[0];
                Model.MilkCollectionId = Convert.ToInt32(_dr["MilkCollectionId"]);
                txtCode.Text = _dr["Code"].ToString();
                txtName.Text = _dr["Name"].ToString();
                txtCode.Text = _dr["Code"].ToString();
                cmbShift.SelectedValue = _dr["Shift"];
                dtDate.Value = Convert.ToDateTime(_dr["Date"]);
                cmbMilkType.SelectedValue = _dr["MilkType"];
                txtLiter.Text = _dr["Quantity"].ToString();
                txtFat.Text = _dr["Fat"].ToString();
                txtRate.Text = _dr["Rate"].ToString();
                txtAmt.Text = _dr["Amount"].ToString();
                FatRate = Convert.ToDecimal(txtRate.Text) / Convert.ToDecimal(txtFat.Text);

                txtCode_Leave(null, null);
            }
            else
            {
                ResetForm();
            }
        }

        private void txtCode_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtCode.Text))
                return;
            _blSabhasad.Search("Code = '" + txtCode.Text + "'");
            if (_DSSearch.Tables.Contains("Sabhasad") && _DSSearch.Tables["Sabhasad"].Rows.Count > 0)
            {
                txtName.Text = _DSSearch.Tables["Sabhasad"].Rows[0]["Name"].ToString();
                _SabhasadId = Convert.ToInt32(_DSSearch.Tables["Sabhasad"].Rows[0]["SabhasadId"]);
                txtName.Enabled = false;

                _blMilkCollection.Search("SabhasadId = " + _SabhasadId);
                if (_DSSearch.Tables.Contains("MilkCollection") && _DSSearch.Tables["MilkCollection"].Rows.Count > 0)
                {
                    txtDaysCollected.Text = _DSSearch.Tables["MilkCollection"].Rows.Count.ToString();
                }
            }
            else
            {
                txtName.Clear();
            }
            ShowPreviousData();
        }

        private void ShowPreviousData()
        {
            if (_SabhasadId == 0)
                return;
            _blMilkCollection.Search("SabhasadId = " + _SabhasadId);
            if (_DSSearch.Tables.Contains("MilkCollection") && _DSSearch.Tables["MilkCollection"].Rows.Count > 0)
            {
                DataRow[] _drArr = _DSSearch.Tables["MilkCollection"].Rows.Cast<DataRow>().OrderByDescending(r => r["Date"]).Where(r => Convert.ToDecimal(r["Shift"]) == Convert.ToDecimal(cmbShift.SelectedValue)).ToArray();
                if (_drArr.Length > 0)
                {
                    txtPreviousFat.Text = _drArr[0]["Fat"].ToString();
                    txtPreviousLtr.Text = _drArr[0]["Quantity"].ToString();
                }
            }
        }

        private void CalculateAmount()
        {
            decimal _Ltr = 0;
            decimal _Fat = 0;
            decimal.TryParse(txtLiter.Text, out _Ltr);
            decimal.TryParse(txtFat.Text, out _Fat);
            txtRate.Text = (_Fat * FatRate).ToString();
            txtAmt.Text = (_Ltr * _Fat * FatRate).ToString();
        }

        private void txtFat_TextChanged(object sender, EventArgs e)
        {
            CalculateAmount();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            ResetForm();
        }

        bool fatHasDot = false;
        private void txtFat_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
            {
                // Allow Digits and BackSpace char 
            }
            else if (e.KeyChar == '.' && !fatHasDot)
            {
                //Allows only one Dot Char 
                fatHasDot = true;
            }
            else { e.Handled = true; }
        }

        bool rateHasDot = false;
        private void txtRate_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
            {
                // Allow Digits and BackSpace char 
            }
            else if (e.KeyChar == '.' && !rateHasDot)
            {
                //Allows only one Dot Char 
                rateHasDot = true;
            }
            else { e.Handled = true; }
        }

        private void btnSelectSabhasad_Click(object sender, EventArgs e)
        {
            frmSearch_Eng _frmSearch = new frmSearch_Eng();
            _frmSearch.Hidden_Field.AddRange(new[] { "SabhasadId" });
            _frmSearch.BusinessClass = _blSabhasad;
            _frmSearch.EditButton.Text = "Select";
            _frmSearch.ShowDialog();
            if (_frmSearch.PressedButton == Press_Button.Edit)
            {
                DataRow _dr = _DSSearch.Tables["Sabhasad"].Rows[0];

                _SabhasadId = Convert.ToInt32(_dr["SabhasadId"]);
                txtCode.Text = _dr["Code"].ToString();
                txtName.Text = _dr["Name"].ToString();
            }
        }

        private void cmbShift_SelectedIndexChanged(object sender, EventArgs e)
        {
            _blMilkCollection.Search("Convert(varchar,Date,112) = '" + dtDate.Value.ToyyyyMMdd_112() + "' and Shift = " + cmbShift.SelectedValue);
            if (_DSSearch.Tables.Contains("MilkCollection") && _DSSearch.Tables["MilkCollection"].Rows.Count > 0)
            {
                DataTable _dtMilkCollection = _DSSearch.Tables["MilkCollection"];
                lblTotalMilk.Text = _dtMilkCollection.Rows.Cast<DataRow>().Sum(dr => Convert.ToDecimal(dr["Quantity"])).ToString();
                lblTotalSabhasad.Text = _dtMilkCollection.Rows.Cast<DataRow>().Select(dr => dr["SabhasadId"]).Distinct().Count().ToString();
                lblTotalAmount.Text = _dtMilkCollection.Rows.Cast<DataRow>().Sum(dr => Convert.ToDecimal(dr["Amount"])).ToString();
                lblAvgFat.Text = Math.Round(_dtMilkCollection.Rows.Cast<DataRow>().Average(dr => Convert.ToDecimal(dr["FAT"])), 2).ToString();
            }
            else
                lblTotalMilk.Text = lblTotalAmount.Text = lblTotalSabhasad.Text = lblAvgFat.Text = string.Empty;
        }

        private void dtDate_ValueChanged(object sender, EventArgs e)
        {
            cmbShift_SelectedIndexChanged(null, null);
        }

        private void txtLiter_TextChanged(object sender, EventArgs e)
        {
            CalculateAmount();
        }
    }
}
